<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\RoleMenu;
use app\common\model\Menu;
use think\Db;
/**
 * 首页接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function login()
    {
        $publicKey='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBT2vr+dhZElF73FJ6xiP181txKWUSNLPQQlid6DUJhGAOZblluafIdLmnUyKE8mMHhT3R+Ib3ssZcJku6Hn72yHYj/qPkCGFv0eFo7G+GJfDIUeDyalBN0QsuiE/XzPHJBuJDfRArOiWvH0BXOv5kpeXSXM8yTt5Na1jAYSiQ/wIDAQAB';
        $mockServer=true;
        // 3. 查询用户角色
        $roleIds = 1;
        $account = $this->request->post('username');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->auth->login($account, $password);

        if ($ret) {
            $staff=$this->auth->getUserinfo();
            $role_id=$staff['role_id'];
            $menuTree=$this->getRoleMenu($role_id);
            $data = [
                'publicKey'=>$publicKey,
                'mockServer'=>$mockServer,
                'tokenName'=>'123',
                'accessToken'=>$staff['token'],
                'menu'=>$menuTree,
                'username'=>$account,
                'permissions'=>['admin', 'editor']];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }

    }


    public function getUser(){

        $user=$this->auth->getUser();



    }
    public function getRoleMenu($roleIds){
        // 4. 查询该角色下所有菜单
        $menuIds = RoleMenu::where('role_id', $roleIds)->column('menu_id');
// 5. 查询菜单详情
        $menus = Db::name('menu')
            ->where('hidden',0)
            ->where('id', 'in', $menuIds)
            ->order('id asc')
            ->select();

        // 6. 组装菜单树
        $menuTree = $this->buildMenuTree($menus);

        return $menuTree;

    }

    private function buildMenuTree($menus, $parentId = 0)
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu['parent_id'] == $parentId) {
                $children = $this->buildMenuTree($menus, $menu['id']);
                $node = [
                    'path' => $menu['path'],
                    'component' => $menu['component'],
                    'name' => $menu['name'],
                    'meta' => [
                        'title' => $menu['title'],
                        'icon' => $menu['icon'],
                        // 你可以加权限、actions等
                    ],
                ];
                if ($children) {
                    $node['children'] = $children;
                }
                $tree[] = $node;
            }
        }
        return $tree;
    }


     public function publicKey()
    {
        $publicKey='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBT2vr+dhZElF73FJ6xiP181txKWUSNLPQQlid6DUJhGAOZblluafIdLmnUyKE8mMHhT3R+Ib3ssZcJku6Hn72yHYj/qPkCGFv0eFo7G+GJfDIUeDyalBN0QsuiE/XzPHJBuJDfRArOiWvH0BXOv5kpeXSXM8yTt5Na1jAYSiQ/wIDAQAB';
        $mockServer=true;

       $this->success('成功',[
           'publicKey'=>$publicKey,
           'mockServer'=>$mockServer,
           'tokenName'=>'123',
           'accessToken'=>'xxxxxx',
    'permissions'=>['admin', 'editor']
       ]);

    }
    public function userInfo()
    {

        $ret = $this->auth->getUser();


        $this->success('成功',[
            'tokenName'=>'test',
            'accessToken'=>'xxxxxx',
            'username'=> $ret['username'],
            'avatar'=>'https://xxx.com/avatar.jpg',
            'permissions'=>['admin', 'editor']
        ]);
    }
    public function logout()
    {
        $this->success('成功',[
            'tokenName'=>'test',
            'accessToken'=>'xxxxxx',
            'username'=> 'admin',
            'avatar'=>'https://xxx.com/avatar.jpg',
            'permissions'=>['admin', 'editor']
        ]);
    }

    /**
     * 获取某个角色的菜单权限树
     * @param int $roleId
     * @return array
     */
    public function getRoleMenuTree($roleId)
    {
        // 1. 查询该角色所有有权限的菜单id
        $menuIds = db('role_menu')->where('role_id', $roleId)->column('menu_id');
        if (empty($menuIds)) {
            return [];
        }
        // 2. 查询所有菜单（可加排序）
        $menus = db('menu')
            ->where('hidden',0)
            ->whereIn('id', $menuIds)
            ->order('sort', 'asc')
            ->select();
        // 3. 转为数组
        $menus = collection($menus)->toArray();
        // 4. 组装成树结构
        return $this->list_to_tree($menus, 'id', 'parent_id', 'children', 0);
    }

    /**
     * 通用的数组转树函数
     * @param array $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    public function list_to_tree($list, $pk = 'id', $pid = 'parent_id', $child = 'children', $root = 0)
    {
        $tree = [];
        $refer = [];
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            $parentId = $data[$pid];
            if ($parentId == $root) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
        return $tree;
    }

}
